/* Utils
 * 基础库封装
 * @Jan
 */

class Utils {
	isString(val) {
		return typeof val === "string";
	}
	isArray(val) {
		return toString.call(val) === "[object Array]";
	}
	isObject(val) {
		return val !== null && typeof val === "object";
	}
	isPlainObject(val) {
		if (toString.call(val) !== "[object Object]") {
			return false;
		}
		var prototype = Object.getPrototypeOf(val);
		return prototype === null || prototype === Object.prototype;
	}
	forEach(obj, fn) {
		if (obj === null || typeof obj === "undefined") {
			return;
		}
		if (typeof obj !== "object") {
			obj = [obj];
		}
		if (this.isArray(obj)) {
			for (var i = 0, l = obj.length; i < l; i++) {
				fn.call(null, obj[i], i, obj);
			}
		} else {
			for (var key in obj) {
				if (Object.prototype.hasOwnProperty.call(obj, key)) {
					fn.call(null, obj[key], key, obj);
				}
			}
		}
	}
	// 深度合并对象
	merge() {
		var result = {};
		function assignValue(val, key) {
			if (this.isPlainObject(result[key]) && this.isPlainObject(val)) {
				result[key] = this.merge(result[key], val);
			} else if (this.isPlainObject(val)) {
				result[key] = this.merge({}, val);
			} else if (this.isArray(val)) {
				result[key] = val.slice();
			} else {
				result[key] = val;
			}
		}

		for (var i = 0, l = arguments.length; i < l; i++) {
			this.forEach(arguments[i], assignValue.bind(this));
		}
		return result;
	}
	// 对象转form-data
	obj2FormData(obj) {
		let data = new FormData();
		for (let key in obj) {
			if (typeof obj[key] == "object") {
				for (let i = 0; i < obj[key].length; i++) {
					data.append(key, obj[key][i]);
				}
			}
			data.append(key, obj[key]);
		}
		return data;
	}
	// 获取urlquery参数
	getQueryVariable(variable) {
		let query = window.location.search.substring(1);
		let vars = query.split("&");
		for (let i = 0; i < vars.length; i++) {
			let pair = vars[i].split("=");
			if (pair[0] == variable) {
				return decodeURI(pair[1]);
			}
		}
		return undefined;
	}
}

// 导出实例化的对象,用于直接访问
let instance = new Utils();
export { Utils, instance as utils };
